package io.itit.ecp.admin.provide.selected;

import io.itit.ecp.admin.common.utils.JsonUtils;
import io.itit.ecp.admin.provide.action.req.DeviceReq;
import io.itit.ecp.admin.provide.action.resp.DeviceResp;
import io.itit.ecp.admin.server.entity.DeviceEntity;
import io.itit.ecp.admin.server.service.IDeviceService;
import io.itit.grass.common.provide.action.resp.SelectedResp;
import io.itit.grass.common.server.selected.ISelected;
import io.itit.grass.common.server.utils.ConvertUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设备选择器
 */
@Component(value = DeviceSelected.CODE)
public class DeviceSelected implements ISelected<SelectedResp> {

    public static final String CODE = "DeviceSelected";

    @Resource
    private IDeviceService deviceService;

    @Override
    public String code() {
        return CODE;
    }

    @Override
    public List<SelectedResp> get(String param) {
        DeviceReq deviceReq = JsonUtils.deserialize(param, DeviceReq.class);
        String sceneProjectId = Objects.nonNull(deviceReq) ? deviceReq.getSceneProjectId() : null;
        String sceneEdificeId = Objects.nonNull(deviceReq) ? deviceReq.getSceneEdificeId() : null;
        String sceneFloorId = Objects.nonNull(deviceReq) ? deviceReq.getSceneFloorId() : null;
        String sceneRoomId = Objects.nonNull(deviceReq) ? deviceReq.getSceneRoomId() : null;
        return deviceService.lambdaQuery()
                .eq(StringUtils.hasLength(sceneProjectId), DeviceEntity::getSceneProjectId, sceneProjectId)
                .eq(StringUtils.hasLength(sceneEdificeId), DeviceEntity::getSceneEdificeId, sceneEdificeId)
                .eq(StringUtils.hasLength(sceneFloorId), DeviceEntity::getSceneFloorId, sceneFloorId)
                .eq(StringUtils.hasLength(sceneRoomId), DeviceEntity::getSceneRoomId, sceneRoomId)
                .list()
                .stream().map(item -> {
                    DeviceResp deviceResp = ConvertUtils.convert(item, DeviceResp.class);
                    return SelectedResp.builder().label(item.getDeviceName())
                            .baseObj(deviceResp)
                            .value(item.getId()).build();
                }).collect(Collectors.toList());
    }
}
